package Prova::Controller::DataSection;

use strict;
use warnings;
use base 'Catalyst::Controller';
use Prova::Checksum;
use Data::Dumper;

=head1 NAME

Prova::Controller::DataSection - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut

=head2 create

create action

=cut

sub create : Private {
    my ( $self, $c ) = @_;

    my $datablock = $c->stash->{datablock};
    my $data = $c->stash->{datasection};

    # delete
    my $datasections = $c->forward( 'find_by_id', [ ( $datablock->id ) ] );
    if ( ref $datasections eq 'ARRAY' ) {
        for my $datasection ( @$datasections ) {
            $c->log->info( "delete data_section : id=".$datasection->id );
            $datasection->delete;
        }
    }

    # CREATE
    if ( ref $data eq 'HASH' ) {
        my @new;
        for my $name ( sort { $data->{$a}->{name} cmp $data->{$b}->{name} } keys %$data ) {
            $data->{$name}->{data_block_id} = $datablock->id;
            # checksum
            $data->{$name}->{checksum} = Prova::Checksum->calc( $data->{$name}->{name} );
            my $datasection = $c->model( 'DBIC::DataSection' )->create( $data->{$name} );
            push @new, $datasection;
            $c->log->info( "create data_section : id=".$datasection->id );
        }
        $c->stash->{datasection} = \@new;
     }
}

=head2 find_by_id

get data section models having datablock_id

=cut

sub find_by_id : Private {
    my ( $self, $c, $datablock_id ) = @_;

    my $datasection = [ $c->model( 'DBIC::DataSection' )->search(
        { data_block_id => $datablock_id },
        { order_by => 'name' }
    ) ];

    return $datasection;
}

=head2 delete

delete action

=cut

sub delete : Local {
    my ( $self, $c, $checksum ) = @_;

    $c->log->debug("=== ".$checksum);
    my $datasection = $c->model( 'DBIC::DataSection' )->search( checksum => $checksum )->first;
    my $datablock_checksum = $datasection->data_block_id->checksum;
    $datasection->delete( $c );

    $c->res->redirect( '/datablock/edit/' . $datablock_checksum );
}

=head1 AUTHOR

Shanon Inc, E<lt>http://www.shanon.co.jp/E<gt>

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;
